import { useEffect, useState, useRef } from 'react';
import type { Card } from '../types';

// 颜色选项
const colorOptions = [
   '#ffffff', // 白色
   '#ffebee', // 浅红
   '#e3f2fd', // 浅蓝
   '#f1f8e9', // 浅绿
   '#fff8e1', // 浅黄
   '#f3e5f5', // 浅紫
   '#e0f7fa', // 浅青
   '#fff3e0', // 浅橙
];

const useColorPicker = () => {
   const [expandedColorPicker, setExpandedColorPicker] = useState<string | null>(null);
   const colorPickerRef = useRef<HTMLDivElement>(null);
   // 关闭颜色选择器当点击外部
   useEffect(() => {
      const handleClickOutside = (event: MouseEvent) => {
         if (colorPickerRef.current && !colorPickerRef.current.contains(event.target as Node)) {
            setExpandedColorPicker(null);
         }
      };
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
         document.removeEventListener('mousedown', handleClickOutside);
      };
   }, []);

   const getColorPicker = (cardId: string, cardcolor: string, updateCard: (id: string, data: Partial<Card>, immediate?: boolean) => void) => (
      <div
         className="color-indicator-container"
         ref={expandedColorPicker === cardId ? colorPickerRef : null}
         style={{ position: 'relative' }}
      >
         <div
            className="color-indicator"
            style={{
               backgroundColor: cardcolor,
               width: 16,
               height: 16,
               borderRadius: '50%',
               cursor: 'pointer',
               border: '1px solid #cbd5e0',
            }}
            onClick={(e) => {
               e.stopPropagation();
               setExpandedColorPicker(expandedColorPicker === cardId ? null : cardId);
            }}
         />

         {expandedColorPicker === cardId && (
            <div className="color-picker-popup">
               {colorOptions.map((color) => (
                  <div
                     key={color}
                     className="color-option"
                     style={{ backgroundColor: color }}
                     onClick={(e) => {
                        e.stopPropagation();
                        setExpandedColorPicker(null);
                        updateCard(cardId, { color }, true);

                     }}
                  />
               ))}
            </div>
         )}
      </div>
   );

   return {
      getColorPicker,
   };
};

export default useColorPicker;
